<template>
  <div class="line-chart-container" ref="chartRef"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'SimpleLineChart',
  props: {
    // 数据格式：{ xData: [], seriesData: [] }
    lineData: {
      type: Object,
      default: () => ({})
    },
    lineColor: {
      type: String,
      default: '#1890ff'
    },
    lineWidth: {
      type: Number,
      default: 2
    },
    smooth: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      chart: null,
      resizeTimer: null
    };
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chart) this.chart.dispose();
  },
  watch: {
    // 修复watch语法：移除嵌套的watch，直接监听lineData
    lineData: {
      deep: true,
      handler(newData) {
        this.updateChart(); // 数据变化时直接重新渲染整个图表（更可靠）
      }
    }
  },
  methods: {
    initChart() {
      const chartDom = this.$refs.chartRef;
      this.chart = echarts.init(chartDom);
      this.updateChart(); // 初始化时渲染
    },

    updateChart() {
      const option = {
        grid: {
          show: false,
          left: 10,
          right: 10,
          top: 15,
          bottom: 0,
          containLabel: false
        },
        xAxis: {
          type: 'category',
          data: this.lineData.xData, // 直接使用xData数组
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: { show: false },
          splitLine: { show: false }
        },
        yAxis: {
          type: 'value',
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: { show: false },
          splitLine: { show: false }
        },
        tooltip: {
          show: false // 关键：隐藏提示框
        },
        // tooltip: {
        //   trigger: 'axis',
        //   backgroundColor: 'rgba(0, 0, 0, 0.7)',
        //   borderColor: 'transparent',
        //   textStyle: { color: '#fff' },
        //   formatter: (params) => {
        //     const param = params[0];
        //     const xData = this.lineData.xData || [];
        //     const xLabel = xData[param.dataIndex] || '未知时间';
        //     const value = param.value || 0;
        //     return `${xLabel}: ${value}`;
        //   }
        // },
        series: [
          {
            // 修复series数据处理：直接使用seriesData数组（数值数组）
            name: '数据',
            type: 'line',
            data: this.lineData.seriesData, // 假设seriesData是[10, 20, 30,...]
            symbol: 'none', // 隐藏折点
          }
        ]
      };

      this.chart.setOption(option);
    },

    handleResize() {
      clearTimeout(this.resizeTimer);
      this.resizeTimer = setTimeout(() => {
        this.chart && this.chart.resize();
      }, 100);
    }
  }
};
</script>

<style lang="scss" scoped>
.line-chart-container {
  width: 100%;
  height: px2vh(70); /* 确保容器有高度，否则图表不显示 */
}
</style>
